package org.hackystat.devcathlon.ui.page.matches;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.model.AbstractReadOnlyModel;
import org.apache.wicket.model.IModel;
import org.hackystat.devcathlon.engine.event.EventScore;

/**
 * Implementation of IDataProvider for Event Scores that keeps track of sort information.
 * 
 * @author John Zhou
 * 
 */
public class SortableEventScoreProvider extends SortableDataProvider {
  /** Support serialization. */
  private static final long serialVersionUID = 1L;
  /** The list for SortableMatchProvider. */
  private List<EventScore> list;
  /** The name of a Match. */
  private String matchName;

  /**
   * Instantiates a SortableEventScoreProvider.
   * 
   * @param list The list to be processed.
   * 
   * @param matchName The name of a Match.
   */
  public SortableEventScoreProvider(List<EventScore> list, String matchName) {
    setSort("date", true);
    this.list = list;
    this.matchName = matchName;
  }

  /**
   * Creates an iterator for SortableEventScoreProvider.
   * 
   * @param first The index of the first element of a list.
   * @param count The count for a list.
   * @return An iterator of a sublist.
   */
  public Iterator<EventScore> iterator(int first, int count) {
    SortParam sp = getSort();
    boolean ascending = sp.isAscending();
    String column = sp.getProperty();
    if (column.compareTo("date") == 0) {
      Collections.sort(list, new EventScoreDateComparator(ascending));
    }
    else if (column.compareTo("event") == 0) {
      Collections.sort(list, new EventNameComparator(ascending, matchName));
    }
    else if (column.compareTo("team") == 0) {
      Collections.sort(list, new EventScoreTeamComparator(ascending));
    }
    else if (column.compareTo("points") == 0) {
      Collections.sort(list, new EventScoreComparator(ascending, matchName));
    }
    return list.subList(first, first + count).iterator();
  }

  /**
   * Creates an IModel for SortableEventScoreProvider.
   * 
   * @param object The object to be modeled.
   * @return The AbstractReadOnlyModel of an object.
   */
  public IModel model(final Object object) {
    return new AbstractReadOnlyModel() {
      /** Support serialization. */
      private static final long serialVersionUID = 1L;

      public Object getObject() {
        return object;
      }
    };

  }

  /**
   * Gets the size of a list.
   * 
   * @return The size of the list.
   */
  public int size() {
    return list.size();
  }
}
